package com.example.autocall2;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.CallLog;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.IOException;
import java.lang.reflect.Method;

public class MainActivity extends Activity implements View.OnClickListener {
    Button buttonStart, buttonStop;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        queryCallLog();
        buttonStart = (Button) findViewById(R.id.Button_Start);
        buttonStop = (Button) findViewById(R.id.Button_Stop);
        buttonStart.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.Button_Start:
                Intent msg = new Intent(this, AutoRedialService.class);
                EditText pnumEdit = (EditText) findViewById(R.id.EditText_phoneNumber);
                EditText retryEdit = (EditText) findViewById(R.id.EditText_RetryCount);
                String phoneNumber = pnumEdit.getText().toString();
                Integer i = Integer.decode(retryEdit.getText().toString());
                int retryCount = i.intValue();
                msg.putExtra("RetryCount", retryCount);
                msg.putExtra("PhoneNumber", phoneNumber);
                // retryEdit.setText(String.valueOf(retryCount-1));
                startService(msg);

                break;
            case R.id.Button_Stop:
                stopService(new Intent(this, AutoRedialService.class));
                break;
            default:
                break;
        }
    }

    @TargetApi(21)
    private void queryCallLog() {
        //  权限检查
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG)
                != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode,
            //      String[] permissions,int[] grantResults)
            // to handle the case where the user grants the permission.
            // See the documentation
            // for ActivityCompat#requestPermissions for more details.
            Log.w("TAG", "permission is request");
            /**
             * 动态申请权限
             * 这里没有在
             * onRequestPermissionsResult(int requestCode,
             * String[] permissions,int[] grantResults)方法里面处理
             *
             */
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_CALL_LOG}, 100);
            return;
        }
        ContentResolver resolver = getContentResolver();
        Log.i("TAG", "query call log " + resolver);
        //获取cursor对象
        Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, new String[]{
                CallLog.Calls.CACHED_FORMATTED_NUMBER,
                CallLog.Calls.CACHED_MATCHED_NUMBER,
                CallLog.Calls.CACHED_NAME,
                CallLog.Calls.TYPE,
                CallLog.Calls.DATE,
                CallLog.Calls.DURATION,
                CallLog.Calls.GEOCODED_LOCATION,
        }, null, null, "date DESC limit 2");

        /**
         *  "date DESC limit 2"
         *  按时间排序查询2条记录
         */

        if (cursor != null) {
            Log.i("TAG", "cursor length is " + cursor.getCount());
            try {
                while (cursor.moveToNext()) {
                    CallRecord record = new CallRecord();
                    record.formatted_number = cursor.getString(0);
                    record.matched_number = cursor.getString(1);
                    record.name = cursor.getString(2);
                    record.type = getCallType(cursor.getInt(3));
                    record.date = cursor.getLong(4);
                    record.duration = cursor.getLong(5);
                    record.location = cursor.getString(6);
                    Log.i("TAG", record.toString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                cursor.close();  //关闭cursor，避免内存泄露
            }
        }
    }
    private String getCallType(int anInt) {
        switch (anInt) {
            case CallLog.Calls.INCOMING_TYPE:
                return "呼入";
            case CallLog.Calls.OUTGOING_TYPE:
                return "呼出";
            case CallLog.Calls.MISSED_TYPE:
                return "未接";
            default:
                break;
        }
        return null;
    }
}
//public class MainActivity extends AppCompatActivity {
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//    }
//
////    public static void endCall(Context cx) { //挂断电话
////        TelephonyManager telMag = (TelephonyManager) cx
////                .getSystemService(Context.TELEPHONY_SERVICE);
////        Class<TelephonyManager> c = TelephonyManager.class;
////        Method mthEndCall = null;
////        try {
////            mthEndCall = c.getDeclaredMethod("getITelephony", (Class[]) null);
////            mthEndCall.setAccessible(true);
////            ITelephony iTel = (ITelephony) mthEndCall.invoke(telMag,
////                    (Object[]) null);
////            iTel.endCall();
////        } catch (Exception e) {
////            e.printStackTrace();
////        }
////    }
//
//    /**
//     * 挂断电话
//     */
//    public void endCall() {
//        try {
//            Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
//            IBinder binder = (IBinder) method.invoke(null, new Object[]{Context.TELEPHONY_SERVICE});
//            ITelephony telephony = ITelephony.Stub.asInterface(binder);
//            assert telephony != null;
//            telephony.endCall();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//    /**
//     * 接听电话
//     */
//    public void answerRingingCall() {
//        try {
//            Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
//            IBinder binder = (IBinder) method.invoke(null, new Object[]{Context.TELEPHONY_SERVICE});
//            ITelephony telephony = ITelephony.Stub.asInterface(binder);
//            telephony.answerRingingCall();
//        } catch (Exception e) {
//            e.printStackTrace();
//            //4.1系统以后的电话接听
//            answerRingingCall_4_1(this);
//        }
//    }
//
//    /**
//     * 4.1版本以上接听电话
//     */
//    private void answerRingingCall_4_1(Context context) {
//        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
//        //模拟无线耳机的按键来接听电话
//        // for HTC devices we need to broadcast a connected headset
//        boolean broadcastConnected = "HTC".equalsIgnoreCase(Build.MANUFACTURER) && !audioManager.isWiredHeadsetOn();
//        if (broadcastConnected) {
//            broadcastHeadsetConnected(context);
//        }
//        try {
//            try {
//                Runtime.getRuntime().exec("input keyevent " +
//                        Integer.toString(KeyEvent.KEYCODE_HEADSETHOOK));
//            } catch (IOException e) {
//                // Runtime.exec(String) had an I/O problem, try to fall back
//                String enforcedPerm = "android.permission.CALL_PRIVILEGED";
//                Intent btnDown = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(
//                        Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN,
//                                KeyEvent.KEYCODE_HEADSETHOOK));
//                Intent btnUp = new Intent(Intent.ACTION_MEDIA_BUTTON).putExtra(
//                        Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP,
//                                KeyEvent.KEYCODE_HEADSETHOOK));
//                context.sendOrderedBroadcast(btnDown, enforcedPerm);
//                context.sendOrderedBroadcast(btnUp, enforcedPerm);
//            }
//        } finally {
//            if (broadcastConnected) {
//                broadcastHeadsetConnected(context);
//            }
//        }
//    }
//    /**
//     * 对HTC的手机，需要进行一点特殊的处理，也就是通过广播的形式，让手机误以为连上了无线耳机。
//     */
//    private void broadcastHeadsetConnected(Context context) {
//        Intent i = new Intent(Intent.ACTION_HEADSET_PLUG);
//        i.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
//        i.putExtra("state", 0);
//        i.putExtra("name", "mysms");
//        try {
//            context.sendOrderedBroadcast(i, null);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
////    private void answerCall(Context cx) { //接听电话
////        TelephonyManager telMag = (TelephonyManager) cx
////                .getSystemService(Context.TELEPHONY_SERVICE);
////        Class<TelephonyManager> c = TelephonyManager.class;
////        Method mthEndCall = null;
////        try {
////            mthEndCall = c.getDeclaredMethod("getITelephony", (Class[]) null);
////            mthEndCall.setAccessible(true);
////            ITelephony iTel = (ITelephony) mthEndCall.invoke(telMag,
////                    (Object[]) null);
////            iTel.answerRingingCall();
////        } catch (Exception e) {
////            e.printStackTrace();
////        }
////    }
//}